<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webssh</title>
    <link rel="icon" href="/static/mystyle/img/favicon.ico"/>
    <link rel="stylesheet" href="/static/webssh/xterm/xterm.css"/>
    <link rel="stylesheet" href="/static/webssh/xterm/style.css"/>
    <link rel="stylesheet" href="/static/webssh/bootstrap.min.css"/>
    <style>
        .input-width {
            width: 20%;
            display: inline-block;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>

<div class="container-fluid">

    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins" id="id-box">
                <div class="ibox-content" id="id-ssh-content" style="padding: 0;">
                    <p style="position:absolute; padding: 0; right:0; margin-right:17px; text-align: center; z-index: 999">
                        <button class="btn btn-danger btn-sm" id="id-close-conn">关闭连接</button>
                    </p>
                    <div id="terminal"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--
<div id="django-webssh-terminal" class="hide">
    <div id="terminal"></div>
</div>
-->

<script src="/static/webssh/jquery.min.js"></script>
<script src="/static/webssh/xterm/xterm.js"></script>
<script src="https://cdn.bootcss.com/xterm/3.14.5/addons/zmodem/zmodem.min.js"></script>
<!--
<script src="/static/webssh/webssh.js"></script>
-->

    <script>
        $("#id-use-pwd").click(function () {
            $('#id-auth-type').html('登录密码');
            $('#id-show-upload').addClass('hide')
        });
        $("#id-use-key").click(function () {
            $('#id-auth-type').html('解密密码');
            $('#id-show-upload').removeClass('hide')
        })
    </script>

    <script>
        function get_box_size() {
            let init_width = 9;
            let init_height = 17;

            let windows_width = $('#id-box').width();
            let windows_height = $(window).height();

            return {
                cols: Math.floor(windows_width / init_width),
                rows: Math.floor(windows_height / init_height),
            }
        }
        var host_id = "{{ host_id }}";

        window.onload=function () {
            let cols = get_box_size().cols;
            let rows = get_box_size().rows;

            //根据div的大小初始化终端，待WebSocket连接上后，显示终端
            let term = new Terminal(
                {
                    cols: cols,
                    rows: rows,
                    useStyle: true,
                    cursorBlink: true
                }
            );
            //组装为ssh连接参数
            //let ssh_args = `user=${user}&host=${host}&port=${port}&auth=${auth}&pwd=${pwd}&sshkey_filename=${sshkey_filename}`;

            let ssh_args = "host_id="+host_id+"&simple_user="+"{{ request.session.username }}";
            //let ws_scheme = window.location.protocol === "https:" ? "wss" : "ws"; //获取协议
            //let ws_port = (window.location.port) ? (':' + window.location.port) : '';  // 获取端口
            //ws = new WebSocket(ws_scheme + '://' + window.location.host + ws_port + '/webssh/?' + ssh_args + `&width=${cols}&height=${rows}`);

            var protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
            var socketURL = protocol + location.hostname + ((location.port) ? (':' + location.port) : '') + '/webssh/?' + ssh_args + '&width=' + cols + '&height=' + rows;

            ws = new WebSocket(socketURL);

            //打开websocket连接，并打开终端
            ws.onopen = function () {
                console.log('WebSocket建立连接，打开Web终端');
                term.open(document.getElementById('terminal'));
            };
            ws.onclose = function (e) {
                console.error('WebSocket关闭连接，关闭Web终端');
                //toastr.success('SSH连接已关闭', '消息');
                //term.write(message);
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            };

            //读取服务器发送的数据并写入web终端
            ws.onmessage = function (e) {
                console.log('WebSocket接收消息，ssh交互中');
                let data = JSON.parse(e.data);

                let message = data['message'];
                if (data.flag === 'msg') {
                    term.write(message);
                } else if (data.flag === 'fail') {
                    term.write(message);  //连接ssh的异常提示
                    //toastr.error(message + "返回登录页", '失败');
                    setTimeout(function () {
                        window.location.reload();
                    }, 3000);
                } else if (data.flag === 'user') {
                    //toastr.info(message, '消息');
                } else if (data.flag === 'error') {
                    //toastr.error(message, '失败');
                    //term.write(message);
                    setTimeout(function () {
                        window.location.reload();
                    }, 5000);
                }
            };

            //向服务器发送数据,flag=1
            term.on('data', function (data) {
                //data为每个按键输入内容，例如按A，就传递给后端：{'flag': 1, 'data': 'a', 'cols': None, 'rows': None}
                let send_data = JSON.stringify({
                    'flag': 'entered_key',
                    'entered_key': data,
                    'cols': null,
                    'rows': null
                });

                //向WebSocket发送消息，也就是输入的每一个按键
                ws.send(send_data)
            });

            //终端右上角显示的关闭连接安装，当点击是，关闭ws
            $('#id-close-conn').click(function () {
                ws.close();
                host_url = window.location.host;
                window.location.href="http://"+host_url+"/cmdb/asset/"
            });

            // 监听浏览器窗口, 根据浏览器窗口大小修改终端大小
            $(window).resize(function () {
                let cols = get_box_size().cols;
                let rows = get_box_size().rows;
                console.log(`更改显示终端窗口大小，行${rows}列${cols}`);
                let send_data = JSON.stringify({'flag': 'resize', 'cols': cols, 'rows': rows});
                ws.send(send_data);
                term.resize(cols, rows) //调整页面终端大小
            })
        }



  </script>

</body>
</html>